package br.com.cs.controller;

import br.com.cs.dao.jdbc.VisitanteJDBC;
import br.com.cs.exception.DAOException;
import br.com.cs.exception.PojoException;
import br.com.cs.model.Visitante;
import br.com.cs.pojo.impl.VisitantePojoImpl;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.ListDataModel;
import javax.faces.validator.ValidatorException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@ManagedBean(name = "visitanteMB")
@RequestScoped
public class VisitanteMB extends AbstractController implements Serializable {

    private ListDataModel visitantes;
    private Visitante visitante;
    private Date data;
    private String filterName;
    private String filterValue;
    private List<Visitante> listaVisitantes = new ArrayList<Visitante>();


    private JasperPrint jasperPrint;
    
    public VisitanteMB() {
        visitante = new Visitante();
    }

    public void setVisitantes(ListDataModel visitantes) {
        this.visitantes = visitantes;
    }

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public String getFilterName() {
        return filterName;
    }

    public void setFilterName(String filterName) {
        this.filterName = filterName;
    }

    public String getFilterValue() {
        return filterValue;
    }

    public void setFilterValue(String filterValue) {
        this.filterValue = filterValue;
    }

    public List<Visitante> getListaVisitantes() {
        return listaVisitantes;
    }

    public void setListaVisitantes(List<Visitante> listaVisitantes) {
        this.listaVisitantes = listaVisitantes;
    }

    public Visitante getVisitante() {
        return visitante;
    }

    public void setVisitante(Visitante visitante) {
        this.visitante = visitante;
    }

    public ListDataModel getVisitantes() {
        try {
            if (visitantes != null) {
                return visitantes;
            } else {
                List visitanteList = VisitantePojoImpl.getInstance().getAll();
                visitantes = new ListDataModel(visitanteList);
                return visitantes;
            }
        } catch (PojoException e) {
            addError(null, e.getSummaryMessage(), e.getDetailsMessage());
            return null;
        }
    }

    public String salvar() throws PojoException, DAOException {

        try {
            if (null != this.visitante.getId()) {
                VisitantePojoImpl.getInstance().save(visitante);
                addInfo(null, "Informação! ERRO", "Visitante atualizada com sucesso");
                return "formVisitante";
            } else {
                VisitanteJDBC.getInstance().save(visitante);
                addInfo(null, "Informação! OK", "Visitante adicionada com sucesso");
                return "formVisitante";
            }

        } catch (PojoException e) {
            addError(null, e.getSummaryMessage(), e.getDetailsMessage());
            return "formVisitante";
        }

    }

    public String criarNovo() {
        this.visitante = new Visitante();
        return "formVisitante";
    }

    public String editar() {
        this.visitante = (Visitante) visitantes.getRowData();
        return "formVisitante";
    }

    public String remover() {
        visitante = (Visitante) visitantes.getRowData();
        try {
            VisitantePojoImpl.getInstance().delete(visitante);
            addInfo(null, "Informação! ", "Visitante removido com sucesso");
            visitantes = null;
            return "listaVisitante";
        } catch (PojoException e) {
            addError(null, e.getSummaryMessage(), e.getDetailsMessage());
            return "listaVisitante";
        }
    }

    public void validaData(FacesContext context, UIComponent comp,
            Object valor) throws ValidatorException {
        Date cData = (Date) valor;
        if (cData.before(new Date())) {
            throw new ValidatorException(new FacesMessage("Data inválida. Digite uma data maior que o dia de hoje."));
        }
    }

    public String filtrar() {
        try {
            if (this.filterValue == null || "".equals(this.filterValue.trim())) {
                visitantes = null;
            } else {
                List visitantesList = VisitantePojoImpl.getInstance().getByFilter(this.filterName.trim(), this.filterValue.trim());
                visitantes = new ListDataModel(visitantesList);
            }
        } catch (PojoException e) {
            addError(null, e.getSummaryMessage(), e.getDetailsMessage());
            return null;
        }
        return "listaVisitante";
    }
    
    public void PDF(ActionEvent actionEvent) throws JRException, IOException, PojoException{
        ServletOutputStream servletOutputStream = null;
        try {
            init();
            HttpServletResponse httpServletResponse = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
            httpServletResponse.addHeader("Content-disposition", "inline; filename=report.pdf");
            servletOutputStream = httpServletResponse.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);    
        } catch (PojoException ex) {
            addError(null, ex.getSummaryMessage(), ex.getDetailsMessage());
        } catch (Exception e) {
            addError(null, "Erro interno! ", e.getMessage());
        }finally{
            servletOutputStream.close();
        }   
    }
    
    public void XML(ActionEvent actionEvent) throws JRException, IOException, PojoException{
        ServletOutputStream servletOutputStream = null;
        try {
            init();
            HttpServletResponse httpServletResponse = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
            httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.xml");
            servletOutputStream = httpServletResponse.getOutputStream();
            JasperExportManager.exportReportToXmlStream(jasperPrint, servletOutputStream);    
        } catch (PojoException ex) {
            addError(null, ex.getSummaryMessage(), ex.getDetailsMessage());
        } catch (Exception e) {
            addError(null, "Erro interno! ", e.getMessage());
        }finally{
            servletOutputStream.close();
        }   
    }
    
     public void init() throws JRException, PojoException{
     listaVisitantes = VisitantePojoImpl.getInstance().getAll();
     JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listaVisitantes);
     FacesContext ctx = FacesContext.getCurrentInstance();
     String dirArquivoJasper = ctx.getExternalContext().getRealPath("\\resources\\report\\RelatorioCategorias.jasper");
     jasperPrint = JasperFillManager.fillReport(dirArquivoJasper, new HashMap(), beanCollectionDataSource);
     }
    
     
}
